#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>

#include "Log.hpp"
#include "LockGuard.hpp"
#include "Common.hpp"
#include "nocopy.hpp"
#include "Inet_Addr.hpp"

using namespace LogModule;

static const int g_socketfd = -1;

class UdpServer : public nocopy
{
public:
    UdpServer(uint16_t port)
        : _socketfd(g_socketfd), _port(port), _isrunning(false)
    {
    }

    void Init()
    {
        // 创建 socketfd
        _socketfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketfd < 0)
        {
            LOG(FATAL, "socket error\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket success\n");

        // 创建 存储 本地 端口ip 信息的结构体
        struct sockaddr_in local;           // 创建sockaddr_in
        bzero(&local, sizeof(local));       // 初始化
        local.sin_family = AF_INET;         // 网络通信
        local.sin_port = htons(_port);      // 绑定端口
        local.sin_addr.s_addr = INADDR_ANY; // 表示服务器端绑定任意ip
        // socket 与 本地的 端口、ip 信息绑定
        int n = ::bind(_socketfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind success\n");
    }

    void Start()
    {
        _isrunning = true;
        char message[1024]; // 接收消息的数组
        while (true)
        {
            // 记录发送方的 端口和ip 信息
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // 接收消息
            ssize_t n = ::recvfrom(_socketfd, message, sizeof(message) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                // 在做后一个字符的后面补上 \0
                message[n] = 0;
                // std::cout << "[client say]# " << message << std::endl;
                Inet_Addr addr(peer);
                std::cout << "[" << addr.Ip() << ":" << addr.Port() << "]# " << message << std::endl;
                // 处理消息
                std::string echo_server = "[udp_server]# ";
                echo_server += message;
                // 响应给客户端
                ssize_t m = ::sendto(_socketfd, echo_server.c_str(), echo_server.size(), 0, (struct sockaddr *)&peer, len);
                if (m < 0)
                {
                    LOG(WARNING, "sendto error\n");
                }
                // LOG(DEBUG, "sendto success\n");
            }
            else
            {
                LOG(WARNING, "recvfrom error\n");
            }
        }
    }

    ~UdpServer()
    {
        if (_socketfd > g_socketfd)
            ::close(_socketfd);
    }

private:
    int _socketfd;   // socket
    uint16_t _port;  // 端口号
    bool _isrunning; // 状态
};